package org.ucas.faker.common.tech;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class PatentFeaturizeRegularRule {
	private final static boolean Flag_SHOW_MATCHFeature = false;
	private final static boolean Flag_SHOW_MATCHEffect = true;
	private List<Pattern> features = null;
	private List<Pattern> effects = null;
	private PatentFeaturizeRegularRule(){
		features = new ArrayList<>();
		effects = new ArrayList<>();
		try {
			InputStream is = this.getClass().getClassLoader().getResourceAsStream("feature_regular.rule");
			
            InputStreamReader read = new InputStreamReader(is);//考虑到编码格式
            BufferedReader featureReader =  new BufferedReader(read);
            String lineTxt = null;
            while((lineTxt = featureReader.readLine()) != null){
                //System.out.println(lineTxt);
                features.add(Pattern.compile(lineTxt));
            }
            read.close();
	    } catch (Exception e) {
	        System.out.println("Error reading feature_regular.rule");
	        e.printStackTrace();
	    }
		
		
		try {			
			InputStream is = this.getClass().getClassLoader().getResourceAsStream("effect_regular.rule");
	        InputStreamReader read = new InputStreamReader(is);//考虑到编码格式
	        BufferedReader featureReader =  new BufferedReader(read);
	        String lineTxt = null;
	        while((lineTxt = featureReader.readLine()) != null){
	            //System.out.println(lineTxt);
	            effects.add(Pattern.compile(lineTxt));
	        }
	        read.close();
	    } catch (Exception e) {
	        System.out.println("Error reading effect_regular.rule");
	        e.printStackTrace();
	    }		
	}
	
	private static PatentFeaturizeRegularRule singleton = null;
	
	public static PatentFeaturizeRegularRule getInstance(){
		if(singleton==null){
			singleton = new PatentFeaturizeRegularRule();
		}
		return singleton;
		
	}

	
	public void displayResult(Map<String,List<String>> map){
		List<String> l = map.get("feature");
		System.out.print("Feature: ");
		for(String s : l){
			System.out.print(s+"\t");
		}
		
		l = map.get("effect");
		System.out.print("\nEffect: ");
		for(String s : l){
			System.out.print(s+"\t");
		}
		
		l = map.get("unknown");
		System.out.print("\nUnknown: ");
		for(String s : l){
			System.out.print(s+"\t");
		}
		
	}
	
	
	//统计多个匹配的规则
	public List<String> featurizeStringByScore(String abs,List<String> lkeyword,String sent_prop){
		List<String> res = new ArrayList<>();

		//System.out.println("abs "+abs);
		String [] sents = abs.split("。\\|.");
		/*
		System.out.println(sents.length);
		for(String s:sents){
			System.out.println("a: " +s);
		}
		*/
		
		Map<String,Double> fscore = new HashMap<>();
		Map<String,Double> escore = new HashMap<>();
		
		for(String s:lkeyword){
			//System.out.println(s);
			fscore.put(s, 0.0);
			escore.put(s, 0.0);
		}
		
		//feature score
		for(String s:sents){
			for(Pattern pattern : features){
                Matcher matcher = pattern.matcher(s);
                
                if(matcher.find()){
                    //System.out.println("sent feature:\t"+pattern.pattern()+"\t"+matcher.group(0));
                	if(matcher.groupCount()<=0) continue;
                    //System.out.println("\n\n"+matcher.groupCount());
                	for(int i=1;i<=matcher.groupCount();i++){
                		String g = matcher.group(i);
                		if(g.length()<=0) continue;
                		//System.out.println("\t\t"+matcher.group(i));
                		for(String w:lkeyword){
                			if(g.indexOf(w)>=0){
                				//System.out.println("feature:\t"+w);
                				fscore.put(w, fscore.get(w)+1);
                			}
                		}
                	}
                }
                else{
                	//System.out.println("not match");
                }
			}
		}
		
		//effect score
		for(String s:sents){
            //System.out.println("sent:\t"+s);
			for(Pattern pattern : effects){
                Matcher matcher = pattern.matcher(s);
                if(matcher.find()){
                    //System.out.println("sent effect:\t"+pattern.pattern()+"\t"+matcher.group(0));
                	if(matcher.groupCount()<=0) continue;
                    //System.out.println("effect:\t"+matcher.groupCount());
                	for(int i=1;i<=matcher.groupCount();i++){
                		String g = matcher.group(i);
                		if(g.length()<=0) continue;
                		//System.out.println("\t\t"+matcher.group(i));
                		for(String w:lkeyword){
                			if(g.indexOf(w)>=0){
                				//System.out.println("effect:\t"+w);
                				escore.put(w, escore.get(w)+1.2);
                			}
                		}
                	}
                }
                else{
                	//System.out.println("not match");
                }
			}
		}
		
		
		for(Entry<String,Double> entry:fscore.entrySet()){
			System.out.println(entry.getKey()+"\t"+entry.getValue()+"\t"+escore.get(entry.getKey()));
		}
		
		List<String> fealist = new ArrayList<>();
		List<String> efflist = new ArrayList<>();
		
		for(String word:lkeyword){
			if(fscore.get(word)>=escore.get(word)){
				fealist.add(word);
			}else{
				efflist.add(word);
			}
			//System.out.print("\tentry.getKey()+"\t"+entry.getValue()+"\t"+escore.get(entry.getKey()));
		}
		
		System.out.println("\nResult");
		for(String a: fealist)
			System.out.print(a+"  ");
		System.out.println();
		for(String a: efflist)
			System.out.print(a+"  ");
		
		String branch = "";
		String effect = "";
		
		//一个都未匹配到,全部归入branch
		if(fealist.size()==0&&efflist.size()==0){
			for(String s:lkeyword){
				fealist.add(s);
			}
		}

		for(String a: fealist)
			branch += a + "#";
		for(String a: efflist)
			effect += a + "#";

		if(branch.length()<=0) res.add("");
		else res.add(branch.substring(0, branch.length()-1));
		if(effect.length()<=0) res.add("");
		else res.add(effect.substring(0, effect.length()-1));			
		
		return res;

	}
	
	
	public List<String> featurizeString(String abs,List<String> keywords,String sent_prop){
		List<String> res = new ArrayList<>();

		//System.out.println("abs "+abs);
		String [] sents = abs.split("。|\\.");
		/*
		System.out.println(sents.length);
		*/
		/*
		for(String s:sents){
			System.out.println("split by seps: " +s);
		}*/
		
		
		List<String> lkeyword = new ArrayList<>();
		lkeyword.addAll(keywords);
		
		List<String> fealist = new ArrayList<>();
		List<String> efflist = new ArrayList<>();
		
		// effect score
		for (String s : sents) {
			if(lkeyword.size()<=0) break;
			// System.out.println("sent:\t"+s);
			for (Pattern pattern : effects) {
				Matcher matcher = pattern.matcher(s);
				if (matcher.find()) {
					if(Flag_SHOW_MATCHEffect)
						System.out.println("sent effect:\t"+pattern.pattern()+"\t"+matcher.group(0));
					if (matcher.groupCount() <= 0)
						continue;
					// System.out.println("effect:\t"+matcher.groupCount());
					for (int i = 1; i <= matcher.groupCount(); i++) {
						String g = matcher.group(i);
						if (g.length() <= 0)
							continue;
						// System.out.println("\t\t"+matcher.group(i));
						List<String> tmp = new ArrayList<>();
						tmp.addAll(lkeyword);
						for (String w : tmp) {
							if (g.indexOf(w) >= 0) {
								// System.out.println("effect:\t"+w);
								efflist.add(w);
								lkeyword.remove(w);
							}
						}
					}
				} else {
					// System.out.println("not match");
				}
			}
		}

		// feature score
		for (String s : sents) {
			if(lkeyword.size()<=0) break;
			for (Pattern pattern : features) {
				Matcher matcher = pattern.matcher(s);

				if (matcher.find()) {
					// System.out.println("sent feature:\t"+pattern.pattern()+"\t"+matcher.group(0));
					if (matcher.groupCount() <= 0)
						continue;
					// System.out.println("\n\n"+matcher.groupCount());
					for (int i = 1; i <= matcher.groupCount(); i++) {
						String g = matcher.group(i);
						if (g.length() <= 0)
							continue;
						// System.out.println("\t\t"+matcher.group(i));
						List<String> tmp = new ArrayList<>();
						tmp.addAll(lkeyword);
						for (String w : tmp) {
							if (g.indexOf(w) >= 0) {
								// System.out.println("feature:\t"+w);
								fealist.add(w);
								lkeyword.remove(w);
								//System.out.println(lkeyword.size());
							}
						}
					}
				} else {
					// System.out.println("not match");
				}
			}
		}

		

		/*
		System.out.println("\nResult");
		for(String a: fealist)
			System.out.print(a+"  ");
		System.out.println();
		for(String a: efflist)
			System.out.print(a+"  ");
		*/
		
		String branch = "";
		String effect = "";
		
		for(String a: fealist)
			branch += a + "#";
		for(String a: efflist)
			effect += a + "#";
		

		if(branch.length()<=0) res.add("");
		else res.add(branch.substring(0, branch.length()-1));
		if(effect.length()<=0) res.add("");
		else res.add(effect.substring(0, effect.length()-1));			
		
		return res;

	}
	/*
	public void test(){
		int testnum = 0;
		int start = 50;
		int maxtestnum = 60;
		try {
			File file=new File("testcase");
            if(file.isFile() && file.exists()){ //判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                new FileInputStream(file));//考虑到编码格式
                BufferedReader featureReader =  new BufferedReader(read);
                String lineTxt = null;
                while((lineTxt = featureReader.readLine()) != null){
                    if(testnum++>maxtestnum) break;
                    if(testnum<start) {
                    	featureReader.readLine();
                    	continue;
                    }
                    System.out.println("\nTest case"+(testnum+1));
                    System.out.println(lineTxt);
                    featurizeString(lineTxt);
                    featureReader.readLine();
                    
                }
                read.close();
	    }else{
	        System.out.println("Error finding testcase.rule");
	    }
	    } catch (Exception e) {
	        System.out.println("Error reading testcase.rule");
	        e.printStackTrace();
	    }
		
	}
	*/
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		PatentFeaturizeRegularRule pf = PatentFeaturizeRegularRule.getInstance();
		//pf.featurize();
//		/pf.test();
		//PatentFeaturizeRegularRule pf = PatentFeaturizeRegularRule.getInstance();
		//pf.displayResult(pf.featurize(abs,keywords));
		//System.out.println(abs);
		//pf.TestFromFile2("testcase10_1");
	}
	

}
